package com.campuscarbooking.api.service.impl;

import com.campuscarbooking.api.annotation.LogExecutionTime;
import com.campuscarbooking.api.annotation.LogMethod;
import com.campuscarbooking.api.config.RabbitMQConfig;
import com.campuscarbooking.api.dto.message.CacheConsistencyMessage;
import com.campuscarbooking.api.service.CacheConsistencyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
@Slf4j
public class CacheConsistencyServiceImpl implements CacheConsistencyService {

    private final RabbitTemplate rabbitTemplate;
    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    @LogMethod(value = "发送缓存一致性消息", logParams = true)
    @LogExecutionTime("缓存一致性消息发送")
    public void sendCacheConsistencyMessage(CacheConsistencyMessage message) {
        log.info("Sending cache consistency message: {}", message);
        
        // 第一步：先删除缓存
        if (message.getCacheKey() != null) {
            redisTemplate.delete(message.getCacheKey());
            log.info("First cache deletion completed for key: {}", message.getCacheKey());
        }

        // 第二步：发送消息到延时队列，用于第二次删除缓存
        rabbitTemplate.convertAndSend(
                RabbitMQConfig.CACHE_DELAY_EXCHANGE,
                RabbitMQConfig.CACHE_DELAY_ROUTING_KEY,
                message
        );
        log.info("Cache consistency message sent to delay queue successfully");
    }

    @Override
    @LogMethod(value = "处理缓存一致性消息", logParams = true)
    @LogExecutionTime("缓存一致性消息处理")
    public void handleCacheConsistencyMessage(CacheConsistencyMessage message) {
        log.info("Handling cache consistency message: {}", message);
        try {
            // 这是从延时队列中收到的消息，执行第二次删除缓存
            if (message.getCacheKey() != null) {
                redisTemplate.delete(message.getCacheKey());
                log.info("Second cache deletion completed for key: {}", message.getCacheKey());
            }

            // 如果是更新操作，在第二次删除后重新设置缓存
            if ("UPDATE".equals(message.getOperationType()) && message.getData() != null) {
                redisTemplate.opsForValue().set(message.getCacheKey(), message.getData());
                log.info("Cache updated after second deletion for key: {}", message.getCacheKey());
            }
        } catch (Exception e) {
            log.error("Error handling cache consistency message", e);
            // 在实际应用中，这里应该添加重试机制或死信队列处理
        }
    }
} 